package Servants;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import core.Localmessage;

public class UDPServer extends Thread
{
	/** General Declaration **/
	int port = 0;
	MyServiceServerImpl server = null;
	
	public  UDPServer(MyServiceServerImpl Server)
	{
		this.server = Server;
		switch(this.server.getName())
		{
		case "montreal":
			port = 6789;
			break;
		case "toronto":
			port = 6790;
			break;
		case "vancouver":
			port = 6791;
			break;
			
		}
	}
	
	public void run()
	{
		Localmessage mes = new Localmessage();

		
		
		DatagramSocket aSocket = null;
		try{
	    	aSocket = new DatagramSocket(port);
					// create socket at agreed port
			byte[] buffer = new byte[1000];
			System.out.println( this.server.getName() + "'s UDP is also ready ...");
 			while(true){
 				DatagramPacket request = new DatagramPacket(buffer, buffer.length);
  				aSocket.receive(request);   
  				mes.parseMessage(new String(request.getData()));
  				switch(mes.getMessageType())
  				{
  				case"check":
  					//String s = "" + this.server.getItems(mes.getItemID());
  					mes.setCnumberOfItems(this.server.getItems(mes.getItemID()));
  					mes.setMessageType("reply");
  					mes.setState(true);
  					break;
  				case"hold":
  					break;
  				case "buy":
  					if(this.server.localBuy(mes.getItemID(), mes.getNumberOfItems()) == "done")
  					{
  						mes.setState(true);
  					}
  					else
  					{
  						mes.setState(false);
  					}
  					mes.setMessageType("reply");
  					break;
  				case "reply":
  					break;
  				}
  				byte [] m = mes.constructMessage().getBytes();
    			DatagramPacket reply = new DatagramPacket(m, m.length, 
    				request.getAddress(), request.getPort());
    			aSocket.send(reply);
    		}
		}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
		}catch (IOException e) {System.out.println("IO: " + e.getMessage());
		}finally {if(aSocket != null) aSocket.close();}

	}

}
